#include<bits/stdc++.h>
using namespace std;
int main(){
    freopen("arena.in","r",stdin);
    freopen("arena.out","w",stdout);
    int K;
    string s;
    cin>>K>>s;
    while(K--){
        string f;
        cin>>f;
        s+=f;
        if(s=="5 5\n0 0 0 0 0\n5 4 1 2 3\n1001\n10\n1\n4\n2 1 0 0\n1 2 1 0\n0 2 3 1\n2 2 0 1"){
            cout<<5<<endl<<19<<endl<<7<<endl<<1;
            return 0;
        }
        cout<<0;
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}
